// rncs
import React, {Component} from 'react';
import {
  Text,
  StyleSheet,
  View,
  Dimensions,
  TextInput,
  Button,
  Image,
  Alert,
} from 'react-native';

const {width, height} = Dimensions.get('screen');

const rpx = x => (width / 750) * x;

export default class Login extends Component {
  doLogin() {
    const {upwd, uname} = this.state;
    console.log(uname, upwd);

    // POST 请求: 参数和路径要分开
    // GET 请求: 路径?参数=值&参数=值...    路径和参数在一起
    const url = 'http://101.96.128.94:9999/data/user/login.php';
    const body = `uname=${uname}&upwd=${upwd}`;

    // POST请求, 需要特定的配置
    const options = {
      method: 'POST',
      body, //参数
      headers: {
        // 参数的类型是 URL字符串格式
        'content-type': 'application/x-www-form-urlencoded',
      },
    };
    // 测试账号密码:  doudou  123456

    // fetch(路径, 配置项)
    fetch(url, options)
      .then(res => res.json())
      .then(res => {
        console.log(res);
        if (res.code == 200) {
          this.props.navigation.push('Main');
        } else {
          // 注意Alert需要引入
          Alert.alert('提示', '很遗憾, 登录失败. 请检查用户名与密码.', [
            {text: '确定'},
          ]);
        }
      });
  }

  state = {uname: '', upwd: ''}; //双向绑定

  render() {
    return (
      <View style={ss.content}>
        <TextInput
          style={ss.input}
          placeholder="请输入管理员用户名"
          value={this.state.uname}
          onChangeText={uname => this.setState({uname})}
        />
        <TextInput
          value={this.state.upwd}
          onChangeText={upwd => this.setState({upwd})}
          style={ss.input}
          placeholder="请输入用户登录密码"
          secureTextEntry
        />
        <View style={{height: 30}} />
        <Button title="登录" onPress={() => this.doLogin()} />

        <View style={ss.logo}>
          <Image source={require('../assets/logo.png')} />
          <Text style={ss.logo_title}>后台管理系统</Text>
        </View>

        <Text style={ss.copy}>&copy;2017 版权所有, CODEBOY.COM</Text>
      </View>
    );
  }
}

const ss = StyleSheet.create({
  logo_title: {fontSize: rpx(40), color: 'rgb(33, 150, 243)'},
  copy: {marginTop: 60, color: 'gray', textAlign: 'center'},
  input: {fontSize: rpx(40), borderBottomWidth: 1, color: 'black'},
  content: {
    paddingHorizontal: rpx(100),
    paddingTop: rpx(100),
    backgroundColor: 'white',
    height: '100%',
  },
  logo: {
    marginTop: 60,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
});
